<?php

namespace app\api\controller;

use app\api\service\OrderService;
use app\ApiController;
use support\spark\exception\ApiException;

class OrderController extends ApiController
{
    /**
     * 准备下单
     */
    public function index()
    {
        $param = request()->post();

        $orderService = new OrderService();
        $param['user_id'] = \Tinywan\Jwt\JwtToken::getCurrentId();
        $res = $orderService->prepareOrderParam($param);
        $vipConf = getConfByType('shop_user_level');
        $res['data']['vipConf'] = $vipConf;
        return sparkSuccess($res);
    }

    /**
     * 试算
     */
    public function trail()
    {
        $orderService = new OrderService();
        $param = $orderService->doTrial(request()->post(), \Tinywan\Jwt\JwtToken::getCurrentId());
        $param['data']['vipDiscount'] = number_format($param['data']['vipDiscount'], 2);
        $param['data']['coupon'] = number_format($param['data']['coupon']['couponAmount'], 2);
        $param['data']['totalPrice'] = number_format($param['data']['totalPrice'], 2);
        $param['data']['postage'] = number_format($param['data']['postage'], 2);
        $param['data']['realPay'] = number_format($param['data']['realPay'], 2);
        return sparkSuccess($param);
    }

    /**
     * 创建订单
     */
    public function createOrder()
    {
        $param = request()->post();
        if (empty($param['goods'])){
            throw new ApiException('购买商品信息错误',-11);
        }

        if (empty($param['pay_way'])) {
            throw new ApiException('请先开启支付',-10);
        }

        if (empty($param['address_id'])) {
            throw new ApiException('请选择收件地址',-12);
        }

        if (!isset(request()->header()['x-csrf-token'])) {
            throw new ApiException('请求信息错误',-12);
        }
        $param['platform'] = isset(request()->header()['x-csrf-token']) ? request()->header()['x-csrf-token'] : '';
        $orderService = new OrderService();
        $res = $orderService->createOrder($param, \Tinywan\Jwt\JwtToken::getCurrentId());
        return sparkSuccess($res);
    }

    /**
     * 获取订单信息
     */
    public function getOrderInfo()
    {
        $orderService = new OrderService();
        return sparkSuccess($orderService->getOrderInfoByOrderNo(request()->input('order_no')));
    }

    /**
     * 获取支付基础配置
     */
    public function getPayConf()
    {
        $orderService = new OrderService();
        return sparkSuccess($orderService->getPayConfig(\Tinywan\Jwt\JwtToken::getCurrentId()));
    }
}
